package com.izhengyin.orderservice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@RestController
@Slf4j
public class OrderController {
    private final OrderRepository orderRepository;
    private final RestTemplate restTemplate;
    public OrderController(OrderRepository orderRepository,RestTemplate restTemplate){
        this.orderRepository = orderRepository;
        this.restTemplate = restTemplate;
    }
    /**
     * 创建订单
     * @param order
     */
    @PostMapping("/order")
    public boolean createOrder(@RequestBody Order order){
        Assert.notNull(order.getItemId(),"商品ID不能为NULL");
        long itemId = order.getItemId();
        String url = "http://127.0.0.1:10083/inventory/{itemId}/deduct";
        ResponseEntity<Boolean> responseEntity = this.restTemplate.postForEntity(url,null,Boolean.class,itemId);
        boolean success = responseEntity.getStatusCode().equals(HttpStatus.OK)
                && Optional.ofNullable(responseEntity.getBody()).orElse(false);
        //扣库存
        if(!success){
            return false;
        }
        //模拟生成订单延迟
        try {
            Random random = new Random();
            TimeUnit.MILLISECONDS.sleep(50+random.nextInt(50));
        }catch (InterruptedException e){
            log.error(e.getMessage(),e);
        }
        orderRepository.saveAndFlush(order);
        log.info("模拟下单成功 {} ",itemId);
        return true;
    }


    @org.springframework.context.annotation.Configuration
    public static class Configuration{
        @Bean
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
}
